﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using ThoughtWorks.QRCode.Codec;
using Yz.Core.Tools;

namespace Yz.Core.Extensions
{
    public static class QRCodeExtension
    {
        /// <summary>
        ///     生成二维码图片
        /// </summary>
        /// <param name="content">填充二维码信息</param> 
        /// <returns></returns>
        public static Bitmap ToQRCodeBitmap(this string value)
        {
            string resmsg = "";
            var qrEncoder = new QRCodeEncoder
            {
                //编码方式(注意：BYTE能支持中文，ALPHA_NUMERIC扫描出来的都是数字)
                QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
                QRCodeScale = 4, //大小(值越大生成的二维码图片像素越高)
                QRCodeVersion = 0, //版本(注意：设置为0主要是防止编码的字符串太长时发生错误)
                QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M
            };
            try
            {
                var qrcode = qrEncoder.Encode(value, Encoding.UTF8);
                resmsg = "生成成功";
                return qrcode;
            }
            catch (IndexOutOfRangeException ex)
            {
                YzNLog.Error(ex);
                resmsg = "超出当前二维码版本的容量上限，请选择更高的二维码版本！";
                YzNLog.Error(resmsg);
                return new Bitmap(100, 100);
            }
            catch (Exception ex)
            {
                YzNLog.Error(ex);
                resmsg = "生成二维码出错！";
                YzNLog.Error(resmsg);
                return new Bitmap(100, 100);
            }
        }
        public static void SaveQRCodeImage(this string value, ImageFormat imageFormat, string path)
        {
            Bitmap bitmap = value.ToQRCodeBitmap();
            bitmap.SaveQRCode(path, imageFormat);
        }
        /// <summary>
        ///     保存二维码，并为二维码添加白色背景。
        /// </summary>
        /// <param name="path"></param>
        public static void SaveQRCode(this Bitmap bimg, string path, ImageFormat imageFormat)
        {
            if (bimg != null && !string.IsNullOrEmpty(path))
            {
                var bitmap = new Bitmap(bimg.Width + 30, bimg.Height + 30);
                var g = Graphics.FromImage(bitmap);
                g.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height);
                g.DrawImage(bimg, new PointF(15, 15));
                bitmap.Save(path, imageFormat);
                g.Dispose();
                bitmap.Dispose();
            }
        }
        /// <summary>
        ///     保存二维码，并为二维码添加白色背景。
        /// </summary>
        /// <param name="path"></param>
        public static void SaveQRCode(this Bitmap bitmap, string path)
        {
            bitmap.SaveQRCode(path, ImageFormat.Png);
        }
    }
}
